package com.hongdee.scm.wareHouse.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.common.service.impl.Common;
import com.hongdee.scm.wareHouse.dao.ITScmWarehouseDao;
import com.hongdee.scm.wareHouse.entity.TScmWarehouse;
import com.hongdee.scm.wareHouse.service.ITScmWarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 名  称:TScmWarehouseServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.wareHouse.service.impl
 * 作  者: 术洪超
 * 日  期:2017-04-28 11:29
 */
@Service
public class TScmWarehouseServiceImpl implements ITScmWarehouseService {

    private String tabName = "T_SCM_WAREHOUSE";
    private String entityName = "TScmWarehouse";

    @Autowired
    private ITScmWarehouseDao itScmWarehouseDao;

    @Override
    public Map page(String start, String limit, String uid, Map data) throws Exception {

        List params = new ArrayList();
        String sql = "select * from " + tabName + " where company_id = ?";
        params.add(TokenUtil.getCompanyId(uid));
        System.out.println(TokenUtil.getCompanyId(uid));
        //判断仓库类型是否为空
        if (data.get("warehouseType") != null && !StringUtils.isEmpty(data.get("warehouseType"))) {
            sql += " and warehouse_type = ? ";
            params.add(data.get("warehouseType"));
        }
        //判断仓库状态是否为空
        if (data.get("status") != null && !StringUtils.isEmpty(data.get("status"))) {
            sql += " and status = ?";
            params.add(data.get("status"));
        }
        return this.itScmWarehouseDao.page(sql, params.toArray(), start, limit);
    }

    /**
     * @param data 要保存的仓库实体
     * @return Map
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @Override
    public TScmWarehouse saveOrUpdate(TScmWarehouse data, String uid) throws Exception {

        //id为空时为添加
        if (data.getId() == null) {

            if (data.getWarehouseName() != null&&!("").equals(data.getWarehouseName())) {
                if (existName(data.getWarehouseName(),uid)) {
                    throw new Exception("该仓库简称已经存在！");
                }
            }
/*            if(data.getWarehouseName() == null||("").equals(data.getWarehouseName())){
                throw new Exception("请输入仓库名称!");
            }*/
            if (data.getWarehouseCode() != null&&!("").equals(data.getWarehouseCode())) {
                if (existCode(data.getWarehouseCode())) {
                    throw new Exception("该仓库代码已经存在！");
                }
            }
/*            if(data.getWarehouseCode() == null||("").equals(data.getWarehouseCode())){
                throw new Exception("请输入仓库代码!");
            }*/
            data.setCreateUser(uid);
            data.setStatus("1");
            data.setCompanyId(TokenUtil.getCompanyId(uid));
            data.setUnitId(TokenUtil.getCompanyId(uid));
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());

        } else {
            //id不为空时则为修改
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());

        }
        data.setCompanyId(TokenUtil.getCompanyId(uid));

        this.itScmWarehouseDao.saveOrUpdate(data);
        return data;
    }

    /**
     * @param uid 登录用户 ID
     * @param id  主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超
     */
    @Override
    public Map info(String id, String uid) throws Exception {

        List params = new ArrayList();
        String sql = "select * from " + tabName + " w where w.company_id = ?";
        params.add(TokenUtil.getCompanyId(uid));

        if (id.equals("") && id.isEmpty()) {
            throw new Exception("id不能为空！");
        }
        sql += " and w.id = ?";
        params.add(id);

        return this.itScmWarehouseDao.info(sql, params.toArray());
    }

    /**
     * @param id 主键 ID
     * @return
     * @throws Exception
     * @desc 启用仓库
     * @author 术洪超
     */

    @Override
    public void start(String id) throws Exception {

        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择仓库！");
        } else {
            String hql = "update " + entityName + " set status = '1',stopDate = '' where id =:id ";
            Map params = new HashMap();
            params.put("id", id);
            this.itScmWarehouseDao.update(hql, params);
        }

    }

    /**
     * @param id 主键 ID
     * @return
     * @throws Exception
     * @desc 停用仓库
     * @author 术洪超
     */
    @Override
    public void stop(String id) throws Exception {


        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择仓库！");
        } else {

            String hql = "update " + entityName + " set status = '0',stopDate = CURRENT_DATE() where id =:id ";
            Map params = new HashMap();
            params.put("id", id);
            this.itScmWarehouseDao.update(hql, params);
        }

    }

    /**
     * @return List<Map>
     * @throws Exception
     * @desc 仓库下拉
     * @author 术洪超
     */

    @Override
    public List<Map> combo(String uid) throws Exception {

        List params = new ArrayList();
        String sql = " select * from " + tabName + " where company_id = ? and status = '1' order by create_time desc";
        params.add(TokenUtil.getCompanyId(uid));
        List<Map<String, Object>> mapList = this.itScmWarehouseDao.list(sql, params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("id"));
            temp.put("label", map.get("warehouseName"));
            resList.add(temp);
        }
        return resList;
    }


    /**
     * @return List<Map>
     * @throws Exception
     * @desc 仓库下拉
     * @author 术洪超
     */

    @Override
    public List<Map> comboIn(String uid, String[] companyId) throws Exception {

        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select w.*,o.o_short_name from " + tabName + " w left join t_bc_organ o on w.company_id = o.id where w.status = '1'");

        if (companyId.length > 0) {
            List<String> companyIdList = new ArrayList<>();
            if("0".equals(companyId[0])||"8a1029015ac58d43015ac65d411e000d".equals(companyId[0])){//集团级
                List<Map<String,Object>> comList = TokenUtil.getDataCompany(uid);
                if(comList.size()>0){
                    for (Map<String,Object> com:comList){
                        companyIdList.add(com.get("id").toString());
                    }
                }else{
                    throw new Exception("数据权限有误！");
                }
            }else{
                companyIdList = Arrays.asList(companyId);
            }
            sql.append(" and w.company_id in ( ");
            for (String company : companyIdList) {
                sql.append(" ? , ");
                params.add(company);
            }
            sql.append(" '' ) ");
        }
        sql.append(" order by w.create_time desc");
        List<Map<String, Object>> mapList = this.itScmWarehouseDao.list(sql.toString(), params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("id"));
            temp.put("label", map.get("warehouseName").toString()+"("+map.get("oShortName").toString()+")");
            resList.add(temp);
        }
        return resList;
    }

    /**
     * @param uid   登录用户 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 查询公司地址，用于添加仓库时的默认地址
     * @author 术洪超
     */

    @Override
    public Map address(String uid) throws Exception {
        List params = new ArrayList();
        String sql = "select o_address from t_bc_organ where id = ?";
        params.add(TokenUtil.getCompanyId(uid));

        return this.itScmWarehouseDao.info(sql, params.toArray());
    }


    /*
    判断仓库编码是否存在，用于保存时判断仓库编码是否重复
     */

    private boolean existCode(String warehouseCode) throws Exception {

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName + " w ");

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if (!warehouseCode.isEmpty() && !warehouseCode.equals("")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" w.warehouse_code = ? ");
            params.add(warehouseCode);
        }

        Map map = this.itScmWarehouseDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    /*
        判断仓库名称是否存在，用于保存时判断仓库名称是否重复
         */
    private boolean existName(String warehouseName,String uid) throws Exception {

        String cid = TokenUtil.getCompanyId(uid);

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName + " w ");

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if(cid!=null&&!cid.equals("")){
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" w.company_id = ? ");
            params.add(cid);
        }
        if (!warehouseName.isEmpty() && !warehouseName.equals("")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" w.warehouse_name = ? ");
            params.add(warehouseName);
        }
        Map map = this.itScmWarehouseDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    /**
     * @param
     * @return Map
     * @throws Exception
     * @desc 仓库转换
     * @author 徐钦勇
     */
    @Override
    public Map convert() throws Exception {
        String sql = " select * from " + tabName + "  ";
        List<Map<String, Object>> mapList = this.itScmWarehouseDao.list(sql);
        Map temp = new HashMap();
        for (Map map : mapList) {
            temp.put(map.get("id"), map.get("warehouseName"));
        }
        return temp;
    }

    /**
     * @param
     * @return Map
     * @throws Exception
     * @desc   仓库转换编号
     * @author 徐钦勇
     */
    @Override
    public Map convertCode() throws Exception {
        String sql = " select * from " + tabName + "  ";
        List<Map<String, Object>> mapList = this.itScmWarehouseDao.list(sql);
        Map temp = new HashMap();
        for (Map map : mapList) {
            temp.put(map.get("id"), map.get("warehouseCode"));
        }
        return temp;
    }
}
